package cn.kgc.itrip.search.dao.imp;

import cn.kgc.itrip.search.dao.SearchHotelDao;
import cn.kgc.itrip.search.entity.HotelSearchVO;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.impl.XMLResponseParser;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Map;

@Repository
public class SearchHotelDaoImpl implements SearchHotelDao {

    private HttpSolrClient client;

    public SearchHotelDaoImpl(){
        String url = "http://localhost:8080/hotel";
        // 创建客户端 指定Solr服务地址
        client = new HttpSolrClient(url);
        // 指定解析器
        client.setParser(new XMLResponseParser());
        // 也可以设定超时时间
//        httpSolrClient.setConnectionTimeout();
    }

    @Override
    public long getHotelCount(SolrQuery solrQuery)throws Exception {
        QueryResponse queryResponse = client.query(solrQuery);
        return queryResponse.getResults().getNumFound();
    }

    @Override
    public List<HotelSearchVO> getHotelListForPaging(SolrQuery solrQuery) throws Exception{
        QueryResponse queryResponse = client.query(solrQuery);
        return queryResponse.getBeans(HotelSearchVO.class);

    }

    @Override
    public List<HotelSearchVO> getHotelListByParams(Map<String, Object> map) throws Exception {
        // 指定查询条件
        SolrQuery solrQuery = new SolrQuery("cityId:"+map.get("cityId"));
        solrQuery.setStart(0);
        solrQuery.setRows((Integer)map.get("count"));
        // 价格升序
        solrQuery.setSort("minPrice",SolrQuery.ORDER.asc);

        QueryResponse queryResponse = client.query(solrQuery);
        // 解析结果 查询对象列表
        return queryResponse.getBeans(HotelSearchVO.class);
    }
}

